<template>
  <div class="app-container calendar-list-container">
    <!-- filter 条件查询 -->
    <div class="filter-container" style="display: flex;align-items: center">
      <!-- <el-date-picker
            v-model="listQuery.startTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:00"
            placeholder="选择开始日期"
            style="width: 200px;margin-right:15px;" class="filter-item"
          ></el-date-picker>
          <el-date-picker
            v-model="listQuery.endTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:00"
            placeholder="选择结束日期"
             style="width: 200px;margin-right:15px;" class="filter-item"
          ></el-date-picker> -->
      <el-input
        @keyup.enter.native="handleFilter"
        clearable
        v-model="listQuery.province"
        style="width: 200px; margin-right: 15px; margin-top: 7px"
        class="filter-item"
        placeholder="请输入省"
      ></el-input>
      <el-button
        type="primary"
        v-waves
        icon="el-icon-search"
        @click="handleFilter"
        >搜索</el-button
      >
      <el-button
        type="primary"
        v-waves
        icon="el-icon-circle-plus-outline"
        @click="beforOpenDialog(1)"
        >添加</el-button
      >
    </div>

    <!-- table 表格 -->
    <el-table
      :data="list"
      v-loading="loading.list"
      element-loading-text="给我一点时间"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column label="序号" prop="index" align="center" width="80px" />
      <el-table-column label="省" prop="province" align="center" />
      <el-table-column
        label="充值金额(元)"
        sortable
        prop="amountInfo"
        align="center"
      />
      <el-table-column
        label="赠送金额(元)"
        sortable
        prop="givenAmountInfo"
        align="center"
      />
      <el-table-column label="创建时间" sortable prop="ctime" align="center" />
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            icon="el-icon-open"
            @click="beforOpenDialog(2, scope.row)"
            type="primary"
            >编辑</el-button
          >
          <el-button
            icon="el-icon-open"
            @click="detele(scope.row.rechargeId)"
            type="danger"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.offset"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 添加代理商弹窗 -->
    <el-dialog :title="diglogTitle" :visible.sync="dialog.add">
      <el-form
        :model="addQuery"
        :rules="bindRules"
        ref="bindForm"
        label-position="right"
        label-width="120px"
        style="textalign: center"
      >
        <el-form-item label="省" required>
          <el-form-item prop="province" style="display: inline-block">
            <el-select
              clearable
              :disabled="this.dialogType === 2"
              style="width: 150px"
              v-model="addQuery.province"
              placeholder="省"
              class="filter-item"
              @change="getCities2(1)"
            >
              <el-option
                v-for="p in provices"
                :label="p.NAME"
                :value="p.AREA_ID"
                :key="p.AREA_ID"
              />
            </el-select>
          </el-form-item>
        </el-form-item>
        <el-form-item label="充值金额(元)" prop="amount">
          <el-input
            type="number"
            clearable
            v-model="addQuery.amount"
            placeholder="请输入充值金额(元)  大于0的两位小数"
          ></el-input>
        </el-form-item>
        <el-form-item label="赠送金额(元)" prop="givenAmount">
          <el-input
            clearable
            v-model="addQuery.givenAmount"
            placeholder="请输入赠送金额(元)  大于或等于0的两位小数"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.add = false">取消</el-button>
        <el-button type="primary" :loading="loading.add" @click="add"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getAddressByAreaId,
  getId,
  getAddress,
  getObjByName,
  getObjByAreaId,
  getByNameProvinceId,
  getByNameCityId,
  getByNameAreaId,
} from "@/utils/getAddress";
import { getList, add, update, del } from "@/api/recharge";
import { validatePhone } from "@/utils/validate";
import { parseTime } from "@/utils";
export default {
  name: "recharge_list",
  data() {
    var validateAmount = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("金额不能为空!"));
      }
      setTimeout(() => {
        var isNum = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
        if (!isNum.test(value)) {
          callback(new Error("请输入正确金额,金额大于0，两位小数以内!"));
        } else {
          if ((value + "").length > 12) {
            callback(new Error("金额超过范围 12位"));
          }
          callback();
        }
      }, 300);
    };
    var validateGivenAmount = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("金额不能为空!"));
      }
      setTimeout(() => {
        var isNum = /^(([0-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
        if (!isNum.test(value)) {
          callback(new Error("请输入正确金额,金额大于等于0，两位小数以内!"));
        } else {
          if ((value + "").length > 12) {
            callback(new Error("金额超过范围 12位"));
          }
          callback();
        }
      }, 300);
    };

    return {
      provices: [],
      cities: [],
      areas: [],
      pId: "",
      cId: "",
      total: 0,
      // 搜索框信息
      listQuery: {
        offset: 1,
        limit: 10,
        isFlag: "",
        startTime: "",
        endTime: "",
        // 导出文件部分信息
        province: "",
      },
      addQuery: {
        rechargeId: "",
        amount: "",
        province: "",
        givenAmount: "",
      },
      bindRules: {
        amount: [
          { required: true, validator: validateAmount, trigger: "blur" },
        ],
        givenAmount: [
          { required: true, validator: validateGivenAmount, trigger: "blur" },
        ],
        province: [{ required: true, message: "请选择省", trigger: "blur" }],
      },
      dialogType: "",
      // 接收的用户列表数据
      list: null,
      // 控制加载动画
      loading: {
        list: false,
        add: false,
      },

      dialog: {
        add: false,
        view: false,
      },

      downloadLoading: false,
    };
  },
  methods: {
    //获取用户列表
    async getList() {
      this.loading.list = true;
      try {
        //调用服务器接口
        const { data } = await getList(this.listQuery);
        this.list = data.records.map((item, index) => ({
          index: index + 1,
          amountInfo: item.amount / 100,
          givenAmountInfo: item.givenAmount / 100,
          ...item,
        }));
        // console.log("lis111"+list)
        this.total = data.total;
      } catch (error) {}
      this.loading.list = false;
    },
    //禁用启用
    changeStatus(userId, status) {
      let type;
      if (status) {
        type = status == 1 ? "启用" : "禁用";
      } else {
        type = "启用";
      }
      this.$confirm(`是否${type}?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          //调用服务器接口
          const { data } = await updateIsFlagUsers({
            userId: userId,
            isFlag: status,
          });
          this.$message({
            type: "success",
            message: `${type}成功!`,
          });
          this.getList();
        })
        .catch(() => {});
    },

    //添加代理商
    async add() {
      this.$refs["bindForm"].validate(async (valid) => {
        if (valid) {
          try {
            let query = {
              rechargeId: this.addQuery.rechargeId,
              province: getAddress(this.addQuery.province),
              amount: this.addQuery.amount * 100,
              givenAmount: this.addQuery.givenAmount * 100,
            };
            this.loading.add = true;
            if (this.dialogType === 1) {
              //调用服务器接口
              const { data } = await add(query);
            } else {
              //调用服务器接口
              const { data } = await update(query);
            }
            this.$message({
              type: "success",
              message: "操作成功",
            });
            this.dialog.add = false;
            this.loading.add = false;
            this.resetForm();
            this.getList();
          } catch (error) {
            this.loading.add = false;
            this.resetForm();
          }
        }
      });
    },

    resetForm(flag) {
      this.$refs.bindForm && this.$refs.bindForm.resetFields();
      if (flag) {
        this.addQuery = {
          id: "",
        };
      }
    },
    beforOpenDialog(type, item) {
      if (type === 1) {
        this.resetForm(1);
      } else {
        const { rechargeId, province, amount, givenAmount } = item;
        this.addQuery = {
          ...this.addQuery,
          rechargeId,
          province,
          amount,
          givenAmount,
        };
        this.addQuery.amount = this.addQuery.amount / 100;
        this.addQuery.givenAmount = this.addQuery.givenAmount / 100;
        this.addQuery.province = getByNameProvinceId(province);
        this.getCities2();
        this.getAreas2();
      }
      this.dialogType = type;
      this.dialog.add = true;
    },
    //删除
    detele(rechargeId) {
      this.$confirm("是否删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        try {
          //调用服务器接口
          const { data } = await del({ rechargeId });
          this.$message({
            type: "success",
            message: "删除成功",
          });
          this.getList();
        } catch (error) {}
      });
    },
    //搜索
    handleFilter() {
      this.listQuery.offset = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.offset = val;
      this.getList();
    },
    //根据fid 查询省、市、区  fid = 0 查询所有省；查询市或者地区 fid 传对应的省areaID
    getAddressByAreaId(fid) {
      return getAddressByAreaId(fid);
    },
    // 获取对应市
    getCities2(type) {
      if (type) {
        this.addQuery.city = "";
        this.addQuery.area = "";
      }
      this.pId = this.addQuery.province;
      this.cities = getAddressByAreaId(this.pId);
    },
    // 获取对应的地区
    getAreas2(type) {
      if (type) {
        this.addQuery.area = "";
      }
      this.pId = this.addQuery.city;
      this.areas = getAddressByAreaId(this.pId);
    },
    // 获取对应市Id
    getCities() {
      this.addQuery.area = "";
      this.areas = [];
      this.cities = getAddressByAreaId(this.pId);
    },
    // 获取对应的地区
    getAreas() {
      this.addQuery.area = "";
      this.areas = getAddressByAreaId(this.cId);
    },
  },
  //开启页渲染
  created() {
    this.getList();
    (this.provices = getAddressByAreaId(0)), this.getCities();
    this.getAreas();
  },
  computed: {
    diglogTitle() {
      return this.dialogType === 1 ? "新增" : "编辑";
    },
  },
};
</script>
